package com.spring.demo.publicutil.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * ReentrantLock 设置线程等待时间线程
 * 上锁：lock
 * 解锁：unlock
 * 设置线程获取锁等待时间 trylock
 *
 * @author youjc
 */
public class T01_ReentrantLock1 {
    Lock lock = new ReentrantLock();

    void m1() {
        lock.lock();
        try {
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println("m1()="+i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    void m2(){
        Boolean locked = false;
        try {
            // lock 等待5秒 超过会报错
            locked = lock.tryLock(5, TimeUnit.SECONDS);
            System.out.println("m2="+locked);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        T01_ReentrantLock1 t = new T01_ReentrantLock1();
        new Thread(t::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(t::m2).start();
    }
}

